import { FC, useEffect, useState } from 'react'
import './index.scss'
import { useDispatch, useSelector } from 'react-redux'
import TabBar from '@/components/tab-bar'
import { FlexCode, DependencyContainer, storeName, TabItem } from '@flex_code/core'
import res from '../../components/tab-bar/res.json'
import DefaultPage from '@/components/default/default'

const Index: FC = () => {
  const dispatch = useDispatch()
  const appStore = useSelector((state: any) => state.app)
  const [tabs, setTabs] = useState<TabItem[]>([
    {
      id: 'id',
      title: '菜单1',
      component: <DefaultPage />,
      icon: '',
      pageId: ''
    }
  ])

  useEffect(() => {
    initApp()
  }, [])

  async function initApp() {
    await initPage()
  }

  async function initPage() {
    // 代理store
    const store: any = new Proxy(appStore, {
      get(target, key: string) {
        return target[key]
      },
      set(target, key, value) {
        target[key] = value
        dispatch({
          type: 'app/test'
        })
        dispatch({
          type: 'app/update',
          payload: {
            [key]: value
          }
        })
        return true
      }
    })
    // 注册store
    DependencyContainer.register(storeName, store)
    const FCC = new FlexCode(store)
    const data = await FCC.parse(res.dataMap.data)
    setTabs(data)
  }

  return <TabBar tabs={tabs} />
}

export default Index
